
/*
** Number -> String; signature
** 将一个时间戳转化成到天数为止的时间字符串; purpose
** const getDate = time => ''; stub
** const getDate = time => (... time); template

** ----------example----------
** getDate(1559530135906) === "2019年6月3日" // true
** getDate(41904000000) === "1971年5月1日" // true
*/

const getDate = (time) => {
  if (!time || typeof time !== 'number') {
    return '未获取到有效时间';
  }
  const oDate = new Date(time);
  const oYear = oDate.getFullYear();
  const oMonth = oDate.getMonth() + 1;
  const oDay = oDate.getDate();
  const oTime = `${oYear}年${oMonth}月${oDay}日`;

  return oTime;
};

/*
** Number -> String; signature
** 将一个时间戳转化成到秒为止的时间字符串; purpose
** const getExactDate = time => ''; stub
** const getExactDate = time => (... time); template

** ----------example----------
** getExactDate(1559530135906) === "2019年6月3日10点48分55秒" // true
** getExactDate(41904000000) === "1971年5月1日8点0分0秒" // true
*/
const getExactDate = (time) => {
  if (!time || typeof time !== 'number') {
    return '未获取到有效时间';
  }

  const oDate = new Date(time);
  const oYear = oDate.getFullYear();
  const oMonth = oDate.getMonth() + 1;
  const oDay = oDate.getDate();
  const oHour = oDate.getHours();
  const oMin = oDate.getMinutes();
  const oSen = oDate.getSeconds();
  const oTime = `${oYear}年${oMonth}月${oDay}日${oHour}点${oMin}分${oSen}秒`;

  return oTime;
};

/*
** Object -> string
** 将一个{ key: value, ... }格式的对象转化成key&value格式的字符串
** const serializeJSON = obj => '';
** const serializeJSON = obj => ( ...obj );

** ----------example----------
** serializeJSON({ a: 1, }) === "a=1"; // true
** serializeJSON({ a: 1, b: 2, }) === "a=1&b=2"; // true
** serializeJSON(null) // throw '请输入一个对象作为参数!';
*/
const serializeJSON = (obj) => {
  // 用来生成错误对象
  function SerializeJSONException(message) {
    this.message = message;
    this.name = 'SerializeJSONException';
  }
  if (obj === null || typeof obj !== 'object') {
    throw new SerializeJSONException('请输入一个对象作为参数');
  }
  const keys = Object.keys(obj);
  const len = keys.length;
  const result = keys.reduce((param, curr, index) => {
    if (index !== len - 1) {
      return `${param}${curr}=${obj[curr]}&`;
    }
    return `${param}${curr}=${obj[curr]}`;
  }, '');

  return result;
};

/*
** String -> String
** 过滤掉字符串中所有的html标签
** const filterHtmlTag = str => '';
** const filterHtmlTag = str => (... str);

** ----------example----------
** filterHtmlTag('<div>123<p>abc</p></div>') === '123abc'; // true
** filterHtmlTag('<div></div>') === ''; // true
*/

// 过滤掉字符串中的html标签
const filterHtmlTag = str => str.replace(/<[^>.]*>/g, '');

export default Object.freeze({
  getDate,
  getExactDate,
  serializeJSON,
  filterHtmlTag,
});
